package shoppingcart.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.xfengshopping.MainActivity;
import com.example.xfengshopping.R;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import LOGIN.login;
import shoppingcart.fragment.adapter.ShopAdapter;
import shoppingcart.fragment.model.ShopList;
import shoppingcart.fragment.utils.HttpUtils;
import utils.TokenUtils;

public class ShoppingcartFragment extends Fragment {
    private Toolbar toolbar;
    private FrameLayout contentContainer;
    private RecyclerView recyclerView;
    private ShopAdapter shopAdapter;
    private List<ShopList> shopList = new ArrayList<>();
    private TextView totalPriceTextView;
    private CheckBox selectAllCheckBox;
    private Button checkoutButton;
    private static final String TAG = "ShoppingCartFragment";
    private Context mContext; // 声明 mContext


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 1. 先加载主布局
        View view = inflater.inflate(R.layout.fragment_cart, container, false);

        // 2. 初始化关键视图组件
        contentContainer = view.findViewById(R.id.contentContainer);
        if (contentContainer == null) {
            Log.e(TAG, "contentContainer 未找到！");
            throw new IllegalStateException("contentContainer 未在布局中找到");
        }

        // 3. 初始化其他组件
        initToolbar(view);
        initBottomBar(view);

        // 4. 加载数据
        loadCartData();

        setHasOptionsMenu(true);
        return view;
    }
    @Override
    public void onResume() {
        super.onResume();
        // 每次回到Fragment都刷新数据
        loadCartData();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext = context; // 初始化 mContext
    }

    private void initBottomBar(View rootView) {
        // 从根视图查找底部栏组件
        totalPriceTextView = rootView.findViewById(R.id.totalPrice);
        selectAllCheckBox = rootView.findViewById(R.id.selectAll);
        checkoutButton = rootView.findViewById(R.id.cost);

        // 添加空检查
        if (selectAllCheckBox == null || checkoutButton == null) {
            Log.e(TAG, "底部栏组件初始化失败");
            return;
        }

        selectAllCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (shopAdapter != null) {
                shopAdapter.selectAllItems(isChecked);
                updateBottomBar();
            }
        });

        checkoutButton.setOnClickListener(v -> {
            if (shopAdapter != null && shopAdapter.getSelectedSum() > 0) {
                // 记录日志
                Log.d(TAG, "用户点击结算按钮，选中的商品数量: " + shopAdapter.getSelectedItemCount());
                Log.d(TAG, "总金额: " + shopAdapter.getSelectedSum());

                // 跳转到地址管理页面
                navigateToAddressManagement();
            } else {
                Toast.makeText(getContext(), "请选择要结算的商品", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initToolbar(View view) {
        toolbar = view.findViewById(R.id.toolbar);
        if (getActivity() instanceof AppCompatActivity) {
            AppCompatActivity activity = (AppCompatActivity) getActivity();
            activity.setSupportActionBar(toolbar);
            if (activity.getSupportActionBar() != null) {
                activity.getSupportActionBar().setDisplayShowTitleEnabled(false);
            }
        }
    }



    private void navigateToAddressManagement() {
        try {
            // 获取选中的购物车项ID数组
            int[] selectedCartItemIds = getSelectedCartItemIds();

            if (selectedCartItemIds.length == 0) {
                Toast.makeText(getActivity(), "请先选择要结算的商品", Toast.LENGTH_SHORT).show();
                return;
            }

            Log.d(TAG, "准备跳转到地址管理，选中的购物车项: " + Arrays.toString(selectedCartItemIds));

            // 创建跳转意图
            Intent intent = new Intent(getActivity(), user.fragment.AddressManagementActivity.class);

            // 设置为选择模式并传递购物车项ID数组
            intent.putExtra("select_mode", true);
            intent.putExtra("cart_item_ids", selectedCartItemIds);

            // 启动Activity
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "跳转到地址管理页面失败", e);
            Toast.makeText(getActivity(), "无法打开地址管理页面", Toast.LENGTH_SHORT).show();
        }
    }

    private int[] getSelectedCartItemIds() {
        List<Integer> selectedIds = new ArrayList<>();
        if (shopAdapter != null) {
            for (int i = 0; i < shopList.size(); i++) {
                if (shopAdapter.isSelected(i)) {
                    selectedIds.add(shopList.get(i).getCartItemId());
                }
            }
        }

        // 转换为基本类型数组
        int[] result = new int[selectedIds.size()];
        for (int i = 0; i < selectedIds.size(); i++) {
            result[i] = selectedIds.get(i);
        }
        return result;
    }


    private void showEmptyView() {
        // 确保contentContainer已初始化
        if (contentContainer == null || getView() == null) return;

        try {
            contentContainer.removeAllViews();
            View emptyView = LayoutInflater.from(getContext())
                    .inflate(R.layout.empty_cart, contentContainer, false);
            contentContainer.addView(emptyView);

            emptyView.findViewById(R.id.go_shopping).setOnClickListener(v -> {
                // 返回首页逻辑
                if (getActivity() instanceof MainActivity) {
                    ((MainActivity) getActivity()).onBackToHome();
                }
            });

            // 隐藏底部结算栏
            View bottomBar = getView().findViewById(R.id.bottomBar);
            if (bottomBar != null) {
                bottomBar.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            Log.e(TAG, "显示空视图失败", e);
        }
    }
    private void showListView(List<ShopList> data) {
        // 确保contentContainer已初始化
        if (contentContainer == null || getView() == null) return;

        try {
            contentContainer.removeAllViews();
            View listView = LayoutInflater.from(getContext())
                    .inflate(R.layout.cart_list, contentContainer, false);
            contentContainer.addView(listView);

            // 显示底部结算栏
            View bottomBar = getView().findViewById(R.id.bottomBar);
            if (bottomBar != null) {
                bottomBar.setVisibility(View.VISIBLE);
            }

            // 初始化RecyclerView
            recyclerView = listView.findViewById(R.id.item_list);
            setupRecyclerView(data);
        } catch (Exception e) {
            Log.e(TAG, "显示列表视图失败", e);
            showEmptyView(); // 失败时回退到空视图
        }
    }
    private void setupRecyclerView(List<ShopList> data) {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));

        shopAdapter = new ShopAdapter(data);
        shopAdapter.setOnItemActionListener(new ShopAdapter.OnItemActionListener() {
            @Override
            public void onItemClick(int position) {
                navigateToProductDetail(shopList.get(position).getGoodsId());
            }

            @Override
            public void onQuantityIncreased(int position, int newQuantity) {
                updateCartItemQuantity(position, newQuantity);
            }

            @Override
            public void onQuantityDecreased(int position, int newQuantity) {
                updateCartItemQuantity(position, newQuantity);
            }

            @Override
            public void onSelectionChanged(int position, boolean isSelected) {
                updateBottomBar();
            }
        });
        recyclerView.setAdapter(shopAdapter);

        if (selectAllCheckBox != null) {
            selectAllCheckBox.setChecked(false);
        }
        updateBottomBar();
    }

    private void loadCartData() {
        String token = TokenUtils.getToken(getActivity());
        Log.d(TAG, "Loading cart data with token: " + token);

        if(token == null || token.length()<10){
            Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
            new Handler().postDelayed(() -> {
                Intent intent = new Intent(mContext, login.class);
                Log.e("skip","跳转到登录");
                // 添加标志清除任务栈
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }, 1000);
        }

        HttpUtils.fetchCartItems(token, new HttpUtils.OnDataReceivedListener() {
            @Override
            public void onDataReceived(List<ShopList> shopLists) {
                if (shopLists == null || shopLists.isEmpty()) {
                    showEmptyView();
                } else {
                    shopList = shopLists;
                    showListView(shopLists);
                }
            }

            @Override
            public void onError(String errorMessage, int statusCode) {
                if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    handleTokenExpired();
                } else {
                    showEmptyView();
                }
            }
        });
    }

    private void updateCartItemQuantity(int position, int newQuantity) {
        String token = TokenUtils.getToken(getActivity());
        int cartItemId = shopList.get(position).getCartItemId();

        HttpUtils.updateCartItemQuantity(token, cartItemId, newQuantity, new HttpUtils.OnUpdateListener() {

            @Override
            public void onSuccess() {
                shopList.get(position).setGoodsCount(newQuantity);
                updateBottomBar();
            }

            @Override
            public void onFailure(String error) {
                getActivity().runOnUiThread(() -> {
                    // 恢复原数量
                    shopAdapter.notifyItemChanged(position);

                    // 更友好的错误提示
                    String errorMsg = "更新数量: " + error;
                    if (error.contains("网络")) {
                        errorMsg += "\n请检查网络连接";
                    } else if (error.contains("登录")) {
                        errorMsg += "\n请重新登录";
                    }

                    Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show();
                    loadCartData();
                });
            }
        });
    }

    private void updateBottomBar() {
        if (shopAdapter == null) return;

        double total = shopAdapter.getSelectedSum();
        int selectedCount = shopAdapter.getSelectedItemCount();
        int totalCount = shopAdapter.getItemCount();

        totalPriceTextView.setText(String.format("¥%.2f", total));

        // 更新全选复选框状态
        selectAllCheckBox.setOnCheckedChangeListener(null);
        selectAllCheckBox.setChecked(selectedCount == totalCount && totalCount > 0);
        selectAllCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            shopAdapter.selectAllItems(isChecked);
        });

        // 更新结算按钮状态
        checkoutButton.setEnabled(selectedCount > 0);
    }

    private void handleTokenExpired() {
        TokenUtils.clearToken(getActivity());
        Toast.makeText(getActivity(), "登录已过期，请重新登录", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(getActivity(), login.class));
        if (getActivity() != null) {
            getActivity().finish();
        }
    }

    private void navigateToProductDetail(int goodsId) {
        // 实现跳转到商品详情页的逻辑
        Toast.makeText(getActivity(), "跳转到商品详情: " + goodsId, Toast.LENGTH_SHORT).show();
    }

    private void checkout() {
        // 实现结算逻辑
        Toast.makeText(getActivity(), "结算总金额: ¥" + shopAdapter.getSelectedSum(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.toolbar_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);

        // 延迟设置可见性，确保菜单已完全初始化
        new Handler().post(() -> {
            MenuItem menuItem = menu.findItem(R.id.action_menu);
            if (menuItem != null) {
                menuItem.setVisible(shopAdapter != null && !shopList.isEmpty());
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_menu) {
            // 确保 Fragment 已附加到 Activity
            if (isAdded() && getView() != null) {
                View menuView = getView().findViewById(R.id.action_menu);
                if (menuView != null) {
                    showPopupMenu(menuView);
                }
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showPopupMenu(View anchorView) {
        if (anchorView == null || getContext() == null) {
            return;
        }

        PopupMenu popup = new PopupMenu(requireContext(), anchorView);
        try {
            popup.getMenuInflater().inflate(R.menu.option, popup.getMenu());

            // 安全地获取菜单项
            MenuItem toggleSelectItem = popup.getMenu().findItem(R.id.selectAll);
            if (toggleSelectItem != null && shopAdapter != null) {
                boolean isAllSelected = shopAdapter.getSelectedItemCount() == shopAdapter.getItemCount();
                toggleSelectItem.setTitle(isAllSelected ? "取消全选" : "全选");
            }

            popup.setOnMenuItemClickListener(menuItem -> {
                if (menuItem.getItemId() == R.id.menu_clear) {
                    clearCart();
                    return true;
                } else if (menuItem.getItemId() == R.id.selectAll) {
                    boolean shouldSelectAll = shopAdapter == null ||
                            shopAdapter.getSelectedItemCount() != shopAdapter.getItemCount();
                    selectAllItems(shouldSelectAll);
                    return true;
                }
                return false;
            });

            popup.show();
        } catch (Exception e) {
            Log.e(TAG, "显示弹出菜单错误", e);
        }
    }

    private void clearCart() {
        // 检查是否有商品可清空
        if (shopList == null || shopList.isEmpty()) {
            Toast.makeText(getActivity(), "购物车已经是空的", Toast.LENGTH_SHORT).show();
            return;
        }

        String token = TokenUtils.getToken(getActivity());
        if (token == null || token.isEmpty()) {
            handleTokenExpired();
            return;
        }


        // 创建一个列表保存所有购物项ID
        List<Integer> cartItemIds = new ArrayList<>();
        for (ShopList item : shopList) {
            cartItemIds.add(item.getCartItemId());
        }

        // 计数器跟踪删除操作
        final int[] successCount = {0};
        final int totalCount = cartItemIds.size();

        // 遍历删除每个购物项
        for (int cartItemId : cartItemIds) {
            HttpUtils.deleteCartItem(token, cartItemId, new HttpUtils.OnUpdateListener() {
                @Override
                public void onSuccess() {
                    successCount[0]++;
                    if (successCount[0] == totalCount) {
                        // 所有删除操作完成
                        getActivity().runOnUiThread(() -> {
                            shopList.clear();
                            if (shopAdapter != null) {
                                shopAdapter.updateData(shopList);
                            }
                            showEmptyView();
                            Toast.makeText(getActivity(), "购物车已清空", Toast.LENGTH_SHORT).show();
                        });
                    }
                }

                @Override
                public void onFailure(String error) {
                    successCount[0]++; // 即使失败也计数，避免阻塞
                    Log.e(TAG, "删除购物项失败: " + error);

                    if (successCount[0] == totalCount) {
                        getActivity().runOnUiThread(() -> {
                            if (successCount[0] < totalCount) {
                                Toast.makeText(getActivity(),
                                        "部分商品删除失败，请重试",
                                        Toast.LENGTH_LONG).show();
                            } else {
                                shopList.clear();
                                if (shopAdapter != null) {
                                    shopAdapter.updateData(shopList);
                                }
                                showEmptyView();
                                Toast.makeText(getActivity(),
                                        "购物车已清空",
                                        Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });
        }
    }

    private void selectAllItems(boolean select) {
        if (shopAdapter != null) {
            shopAdapter.selectAllItems(select);
            updateBottomBar();

            Toast.makeText(getActivity(),
                    select ? "已全选所有商品" : "已取消全选",
                    Toast.LENGTH_SHORT).show();
        }
    }
}